<!--
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-18 11:01:29
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-04-19 12:13:07
 * @FilePath: /free-learning-front/src/views/MyCourseView.vue
 * @Description: 我的课程页面
-->
<template>
  <div class="my-course">
    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-filters">
        <div class="filter-item">
          <el-cascader
            v-model="queryParams.categoryId"
            :options="courseTypes"
            clearable
            placeholder="请选择课程类型"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children',
              emitPath: false,
              expandTrigger: 'click',
            }"
          />
        </div>
        <div class="filter-item">
          <el-select
            v-model="queryParams.status"
            placeholder="课程状态"
            clearable
          >
            <el-option label="未开始" :value="0" />
            <el-option label="学习中" :value="1" />
            <el-option label="已完成" :value="2" />
          </el-select>
        </div>
        <div class="filter-item search-input">
          <el-input
            v-model="queryParams.keyword"
            placeholder="搜索课程"
            clearable
            @keyup.enter="handleQuery"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="filter-item">
          <el-button type="primary" :icon="Search" @click="handleQuery" round
            >搜索</el-button
          >
          <el-button :icon="Refresh" @click="resetQuery" round>重置</el-button>
        </div>
      </div>
    </div>

    <!-- 课程列表 -->
    <div class="course-list" v-loading="loading">
      <!-- 骨架屏 -->
      <div v-if="loading" class="course-grid">
        <div v-for="i in 4" :key="i" class="course-card skeleton">
          <div class="skeleton-header"></div>
          <div class="skeleton-content">
            <div class="skeleton-title"></div>
            <div class="skeleton-info"></div>
            <div class="skeleton-progress"></div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="courseList.length === 0" class="empty-state">
        <el-empty description="暂无课程数据" :image-size="200">
          <template #description>
            <p>您还没有添加任何课程，快去选择感兴趣的课程吧</p>
          </template>
          <el-button type="primary" @click="$router.push('/courses')"
            >去选课</el-button
          >
        </el-empty>
      </div>

      <!-- 课程列表 -->
      <div v-else class="course-grid">
        <div v-for="course in courseList" :key="course.id" class="course-card">
          <div class="course-cover">
            <img :src="course.coverImage" :alt="course.courseName" />
          </div>
          <div class="course-header">
            <div class="course-title" :title="course.courseName">
              {{ course.courseName }}
            </div>
            <span class="category-tag" :title="course.categoryName">{{
              course.categoryName
            }}</span>
            <el-tag :type="getStatusType(course.status)" size="small">
              {{ getStatusText(course.status) }}
            </el-tag>
          </div>
          <div class="course-content">
            <div class="course-info">
              <span
                ><el-icon><User /></el-icon> {{ course.consultantName }}</span
              >
              <span
                ><el-icon><Timer /></el-icon>
                <div>观看至第{{ course.currentChapter }}节</div>
                {{ formatDuration(course.learningDuration) }}</span
              >
            </div>
            <div class="course-progress">
              <span class="progress-text">学习进度</span>
              <el-progress
                :percentage="course.progress * 100"
                :status="course.status === 3 ? 'success' : ''"
              />
            </div>
            <div class="course-footer">
              <span class="last-learn-time">
                <el-icon><Calendar /></el-icon>
                最近学习：{{ formatDate(course.lastLearnTime) }}
              </span>
              <div class="course-actions">
                <el-button
                  type="primary"
                  link
                  @click="
                    $router.push(`/course-learning?courseId=${course.courseId}`)
                  "
                >
                  继续学习
                </el-button>
                <el-popconfirm
                  title="确定要删除这门课程吗？"
                  @confirm="handleDelete(course.id)"
                >
                  <template #reference>
                    <el-button type="danger" link>删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  Search,
  Refresh,
  User,
  Timer,
  Calendar,
} from "@element-plus/icons-vue";
import {
  queryByUser,
  deleteById,
  type UserCourse,
  type ByUserQuery,
} from "@/api/user-course";
import { useCourseTypeStore } from "@/store/modules/courseType";
import { useRouter } from "vue-router";
import moment from "moment";

defineOptions({
  name: "MyCourseView",
});

const router = useRouter();
const loading = ref(false);
const courseList = ref<UserCourse[]>([]);
const courseTypeStore = useCourseTypeStore();
const courseTypes = ref(courseTypeStore.courseTypeList);

// 查询参数
const queryParams = ref<Partial<ByUserQuery>>({
  status: undefined,
  keyword: undefined,
  categoryId: undefined,
});

// 获取课程列表
const getCourseList = async () => {
  try {
    loading.value = true;
    const res = await queryByUser(queryParams.value);
    courseList.value = res;
  } catch (error) {
    console.error("获取课程列表失败:", error);
    ElMessage.error("获取课程列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleQuery = () => {
  getCourseList();
};

// 重置
const resetQuery = () => {
  queryParams.value = {
    status: undefined,
    keyword: undefined,
    categoryId: undefined,
  };
  getCourseList();
};

// 删除课程
const handleDelete = async (id: number) => {
  try {
    await deleteById(id);
    ElMessage.success("删除成功");
    getCourseList();
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败");
  }
};

// 格式化学习时长
const formatDuration = (seconds: number) => {
  if (!seconds) return "0秒";
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes}分${remainingSeconds}秒`;
};

// 格式化日期
const formatDate = (date: string) => {
  if (!date) return "暂无记录";
  return moment(date).format("YYYY-MM-DD HH:mm:ss");
};

// 获取状态类型
const getStatusType = (status: number) => {
  const types = {
    0: "info",
    1: "warning",
    2: "success",
  };
  return types[status as keyof typeof types] || "info";
};

// 获取状态文本
const getStatusText = (status: number) => {
  const texts = {
    0: "未开始",
    1: "学习中",
    2: "已完成",
  };
  return texts[status as keyof typeof texts] || "未知";
};

onMounted(async () => {
  // 确保课程分类数据已加载
  if (courseTypes.value.length === 0) {
    await courseTypeStore.getCourseTypeList();
    courseTypes.value = courseTypeStore.courseTypeList;
  }
  getCourseList();
});
</script>

<style scoped>
.my-course {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.search-section {
  margin-bottom: 32px;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
}

.search-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
}

.filter-item {
  display: flex;
  gap: 12px;
}

.filter-item :deep(.el-input),
.filter-item :deep(.el-select) {
  width: 160px;
}

.filter-item :deep(.el-input__wrapper),
.filter-item :deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #e5e7eb;
}

.filter-item :deep(.el-input__wrapper:hover),
.filter-item :deep(.el-select .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff;
}

.filter-item :deep(.el-button) {
  height: 36px;
  padding: 0 20px;
}

.search-input :deep(.el-input__wrapper) {
  background-color: white;
}

.course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.course-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.course-cover {
  position: relative;
  width: 100%;
  height: 160px;
  overflow: hidden;
  border-radius: 8px 8px 0 0;
}

.course-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.course-card:hover .course-cover img {
  transform: scale(1.05);
}

.course-header {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
}

.category-tag {
  color: #409eff;
  font-size: 14px;
  width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
}

.course-content {
  padding: 12px 16px;
  text-align: left;
}

.course-title {
  width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: left;
  font-size: 15px;
  color: #333;
}

.course-info {
  display: flex;
  gap: 12px;
  color: #666;
  font-size: 13px;
  margin-bottom: 12px;
  align-items: center;
}

.course-info span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.course-progress {
  margin-bottom: 16px;
}

.progress-text {
  display: block;
  margin-bottom: 8px;
  color: #666;
  font-size: 14px;
}

.course-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
}

.last-learn-time {
  color: #666;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.course-actions {
  display: flex;
  gap: 8px;
}

/* 骨架屏样式 */
.skeleton {
  position: relative;
  overflow: hidden;
}

.skeleton-header {
  height: 160px;
  background: #f5f7fa;
  border-radius: 8px 8px 0 0;
}

.skeleton-content {
  padding: 16px;
}

.skeleton-title {
  height: 20px;
  background: #f5f7fa;
  margin-bottom: 16px;
  width: 80%;
}

.skeleton-info {
  height: 16px;
  background: #f5f7fa;
  margin-bottom: 16px;
  width: 60%;
}

.skeleton-progress {
  height: 40px;
  background: #f5f7fa;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.empty-state :deep(.el-empty__description p) {
  color: #909399;
  margin: 10px 0;
}

@media (max-width: 768px) {
  .my-course {
    padding: 16px;
  }

  .search-section {
    padding: 16px;
  }

  .search-filters {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-item {
    width: 100%;
  }

  .filter-item :deep(.el-input),
  .filter-item :deep(.el-select) {
    width: 100%;
  }

  .filter-item :deep(.el-button) {
    flex: 1;
  }

  .course-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
}
</style>
